package com.codeoss.framework.springsecurity;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import com.codeoss.framework.context.ExternalContext;
import com.codeoss.framework.context.YunContext;
import com.codeoss.framework.util.UserUtil;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    
    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UserDetailsService userDetailsService;
    @Autowired
    private UserUtil userUtil;
    @Value("${framework.base-path}")
   	private String basePath;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String authHeader = httpServletRequest.getHeader(this.tokenHeader);
        if(StringUtils.isEmpty(authHeader)) {
        	authHeader=httpServletRequest.getParameter(this.tokenHeader);
        }
        
    	HttpSession httpSession = httpServletRequest.getSession();
		YunContext yunContext = new YunContext();
		ExternalContext externalContext = new ExternalContext();
		externalContext.setHttpSession(httpSession);
		externalContext.setHttpServletRequest(httpServletRequest);
		externalContext.setHttpServletResponse(httpServletResponse);
		YunContext.setCurrentContext(yunContext);
		yunContext.setExternalContext(externalContext);
		
        if (StringUtils.isNotBlank(authHeader)){
            String username = jwtTokenUtil.getUserNameFromToken(authHeader);
            if (StringUtils.isNotBlank(username) && SecurityContextHolder.getContext().getAuthentication() == null) {
                UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
                // 校验token
                if (jwtTokenUtil.validateToken(authHeader, userDetails)) {
                    UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                            userDetails, null, userDetails.getAuthorities());
                    authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(
                            httpServletRequest));
                    SecurityContextHolder.getContext().setAuthentication(authentication);
                }
            }
            yunContext.setToken(authHeader);
            userUtil.init(username,httpServletRequest,httpServletResponse);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
